package mavenWebProject;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Servlet implementation class DeleteAccountServlet
 */
@WebServlet("/DeleteAccountServlet")
public class DeleteAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteAccountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.加载mybatis的核心配置文件，获取sqlsessionfactory
				String resource = "mybatis-config.xml";
				InputStream inputStream = Resources.getResourceAsStream(resource);
				SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
				
				//2.获取sqlsession对象，用它来执行sql
				SqlSession sqlsession=sqlSessionFactory.openSession();
				
				//3.获取mapper接口的代理对象
				userMapper mapper=sqlsession.getMapper(userMapper.class);
				productsMapper pmapper=sqlsession.getMapper(productsMapper.class);
				//4.执行方法
				request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");
				HttpSession session=request.getSession();
				String username=String.valueOf(session.getAttribute("username"));
				mapper.deleteAccount(username);
				pmapper.deleteCarByUsername(username);
				List<order> order=pmapper.selectAllOrder(username);boolean flag=true;
				for (order s:order) {
					if(s.getStage().trim().contentEquals("待收货") || s.getStage().trim().contentEquals("待发货")) {flag=false;}
				}
				if(flag) {sqlsession.commit();request.getRequestDispatcher("messagePage.jsp?message=账户已注销").forward(request, response);}
				else {request.getRequestDispatcher("messagePage.jsp?message=您还有订单未完成").forward(request, response);}
				
				//6.释放资源
				sqlsession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
